using TMPro;
using System;
using Framework.Save;
using LitJson;
using UnityEngine;

namespace GameCore
{
    public class IngredientCell : Cell, IJsonSerializable
    {
        public Action OnItemPlaced;
        
        [Header("Ingredient Cell")] public SimpleWorldItem item;
        public int placedCount;
        public int requiredCount;

        public SpriteRenderer itemSR;
        public Transform itemTransform;
        public TMP_Text countText;

        private void ResizeItem()
        {
            var pixelSize = item.sprite.rect.size;
            var ppu = item.sprite.pixelsPerUnit;
            var units = pixelSize / ppu;
            var scale = Vector2.one / units;
            var uniformScale = Mathf.Min(scale.x, scale.y);
            itemTransform.localScale = new Vector3(uniformScale, uniformScale, uniformScale);
            itemSR.sprite = item.sprite;
        }

        public void Start()
        {
            ResizeItem();
            RefreshText();
        }

        #if UNITY_EDITOR
        private void OnValidate()
        {
            ResizeItem();
            RefreshText();
        }
        #endif

        private void RefreshText()
        {
            countText.text = $"{placedCount}/{requiredCount}";
        }
        
        public bool Match() => placedCount >= requiredCount;

        public override void OnClick()
        {
            if (placedCount <= 0) return;
            var gridItem = PrefabFactory.CreateInstance<GridItem>(item.resourceID);
            gridItem.ResetData();
            PlayerInputHandler.BeginPlaceGridItem(gridItem);
            placedCount -= 1;
            RefreshText();
        }

        public override bool TryPlaceItem(GridItem item)
        {
            if (placedCount >= requiredCount) return false;
            if (this.item.resourceID != item.resourceID) return false;
            placedCount += 1;
            RefreshText();
            OnItemPlaced?.Invoke();
            return true;
        }

        public JsonData Serialize()
        {
            var json = JsonUtil.NewObject();
            json["item"] = item.resourceID.ToString();
            json["placed"] = placedCount;
            json["required"] = requiredCount;
            return json;
        }

        public void Deserialize(JsonData json)
        {
            placedCount = (int)json["placed"];
            requiredCount = (int)json["required"];
            RefreshText();
        }
    }
}